package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient highLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        // 获取查询请求
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        // 布尔查询,添加查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (StringUtils.isNotEmpty(dto.getSearchWords())) {
            // 添加查询条件
            boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));

            // 异步调用,保存用户搜索记录
            ApUser user = ApUserThreadLocalUtil.getUser();
            if (user != null && user.getId() != null) {
                apUserSearchService.insert(dto.getSearchWords(), user.getId());
            }

        } else {
            // 没有传递查询条件,查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 添加过滤条件
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        searchRequest.source().query(boolQuery);

        // 设置分页
        searchRequest.source().from(dto.getPageNum() * dto.getPageSize()).size(dto.getPageSize());

        // 设置排序,时间倒序
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        // 设置搜索结果高亮显示
        searchRequest.source().highlighter(new HighlightBuilder()
                .field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>"));

        // 发送查询请求
        SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 结果解析
        SearchHits hits = searchResponse.getHits();
        long total = hits.getTotalHits().value;

        // 将结果添加到集合中返回
        // 包含正常结果和高亮的结果
        List<Map<String,String>> list = new ArrayList<>();

        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            // 高亮结果
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            // 获取查询结果
            String json = searchHit.getSourceAsString();
            // 将结果转换为map集合
            Map<String, String> resultMap = JSON.parseObject(json, Map.class);

            // 将高亮结果设置到查询出的结果中
            if (highlightFields != null &&highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                Text[] texts = highlightField.getFragments();
                String h_title = StringUtils.join(texts);
                resultMap.put("h_title", h_title);
            } else {
                resultMap.put("h_title", resultMap.get("title"));
            }

            list.add(resultMap);
        }

        return ResponseResult.okResult(list);
    }
}
